import { v4 as uuid4 } from 'uuid'
import { defineAsyncComponent, shallowRef } from 'vue'
import { componentType } from '../config/layoutType'
export const getUUID = (prefix = 'lay') => {
  return `${prefix}${uuid4()}`
}
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}
// 计算最大公约数 (GCD)
export function getGcd(a, b) {
  while (b !== 0) {
    let temp = b
    b = a % b
    a = temp
  }
  return a
}
// 动态加载组件
export function loadComponents(type = 'custom') {
  let componentsList = shallowRef({})
  let models = null
  if (type === 'custom') {
    models = import.meta.glob('../components/custom/*.vue')
  } else if (type === 'preview') {
    models = import.meta.glob('../components/preview/*.vue')
  }
  componentType.forEach(obj => {
    let component = null
    Object.keys(models).forEach(item => {
      if (item.includes(obj.config.key) && obj.config.isShowComponent) {
        component = defineAsyncComponent(models[item])
      }
    })

    componentsList.value[obj.config.key] = component
  })
  return componentsList
}
export function getFileType(url) {
  const extension = url.split('.').pop().toLowerCase()
  if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension)) {
    return 'image'
  } else if (['mp3', 'wav', 'aac', 'flac', 'ogg'].includes(extension)) {
    return 'audio'
  } else if (
    ['mp4', 'mpeg', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', '3gp'].includes(
      extension,
    )
  ) {
    return 'video'
  }
  return 'unknown'
}
export function getMIME(url) {
  const type = url.split('.').pop().toLowerCase()
  let mimeMap = new Map([
    ['mp4', 'video/mp4'],
    ['mpeg', 'video/mpeg'],
    ['avi', 'video/avi'],
    ['mov', 'video/quicktime'],
    ['wmv', 'video/x-ms-wmv'],
    ['flv', 'video/x-flv'],
    ['mkv', 'video/webm'],
    ['3gp', 'video/3gpp'],
    ['mp3', 'audio/mpeg'],
    ['wav', 'audio/wav'],
    ['aac', 'audio/aac'],
    ['ogg', 'audio/ogg'],
  ])
  return mimeMap.get(type) ?? ''
}
export function convertImageToBase64(url) {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.setAttribute('crossOrigin', 'anonymous')
    img.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0)
      const dataURL = canvas.toDataURL('image/png')
      resolve(dataURL)
    }
    img.onerror = err => {
      reject(err)
    }
    img.src = url
  })
}
export function convertVideoToBase64(url, type) {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video')
    video.src = url
    video.setAttribute('crossOrigin', 'Anonymous') // 处理跨域
    video.setAttribute('preload', 'metadata')
    // 设置播放时间
    video.currentTime = 2
    // 当当前帧的数据已加载，但没有足够的数据来播放指定音频/视频的下一帧时触发。
    video.addEventListener('loadeddata', () => {
      const canvas = document.createElement('canvas')
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      const ctx = canvas.getContext('2d')
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
      const dataURL = canvas.toDataURL('image/png')
      resolve({
        dataURL,
        type,
      })
    })
    video.play()
    video.addEventListener('error', err => {
      reject(err)
    })
  })
}
